<template>
  <uni-popup ref="popup" type="bottom">
    <view class="payment-popup">
      <view class="header">
        <text class="title">Payment Details</text>
        <text class="close" @click="close">×</text>
      </view>

      <view class="form">
        <view class="form-item">
          <text class="label">Card Number</text>
          <input
            v-model="form.bankCardId"
            type="text"
            placeholder="Enter card number"
            :disabled="!!savedCard"
          />
        </view>

        <view class="form-row">
          <view class="form-item">
            <text class="label">Expiry (MM/YY)</text>
            <input
              v-model="form.expiry"
              type="text"
              placeholder="MM/YY"
              :disabled="!!savedCard"
              maxlength="5"
              @input="formatExpiry"
            />
          </view>

          <view class="form-item">
            <text class="label">CVV</text>
            <input v-model="form.cvv" type="number" placeholder="CVV" maxlength="3" />
          </view>
        </view>

        <view class="amount">
          <text>Total Amount:</text>
          <text class="price">
            ${{ discountedAmount }}
            <span v-if="isDiscounted" class="discount-label">(Discounted)</span>
          </text>
        </view>

        <button class="pay-btn" @click="handlePayment">Pay Now</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed } from 'vue'
import { saveBankCard, userInfo, canOfferDiscount } from '@/service/user'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const props = defineProps({
  amount: { type: Number, required: true },
  savedCard: { type: Object, default: null },
})

const emit = defineEmits(['success'])
const popup = ref(null)

const form = ref({
  bankCardId: '',
  expiry: '',
  cvv: '',
})

const isDiscounted = ref(false)
const discountedAmount = computed(() => {
  return isDiscounted.value ? (props.amount * 0.8).toFixed(2) : props.amount.toFixed(2)
})

// 如果有已保存的卡，填充表单
const initSavedCard = () => {
  if (props.savedCard) {
    console.log('保存的卡信息:', props.savedCard)
    const { bankCardId, bankCardExpiryMonth, bankCardExpiryYear, bankCardCvv } = props.savedCard

    // 将月份转为字符串并补零
    const formattedMonth = String(bankCardExpiryMonth).padStart(2, '0')
    // 获取年份的后两位
    const formattedYear = String(bankCardExpiryYear).slice(-2)

    form.value = {
      bankCardId: bankCardId || '',
      expiry: bankCardExpiryMonth && bankCardExpiryYear ? `${formattedMonth}/${formattedYear}` : '',
      cvv: bankCardCvv || '', // 使用服务器返回的 CVV
    }
  } else {
    form.value = {
      bankCardId: '',
      expiry: '',
      cvv: '',
    }
  }
}

// 格式化输入的月份和年份
const formatExpiry = (e) => {
  let value = e.detail.value.replace(/\D/g, '')
  if (value.length >= 2) {
    // 确保月份在1-12之间
    const month = parseInt(value.slice(0, 2))
    if (month > 12) {
      value = '12' + value.slice(2)
    } else if (month < 1) {
      value = '01' + value.slice(2)
    }
    value = value.slice(0, 2) + '/' + value.slice(2)
  }
  form.value.expiry = value
}

const handlePayment = async () => {
  try {
    // 模拟支付过程
    uni.showLoading({ title: 'Processing...' })
    await new Promise((resolve) => setTimeout(resolve, 1500))

    // 如果是新卡，保存卡信息
    if (!props.savedCard) {
      const [month, year] = form.value.expiry.split('/')
      await saveBankCard(
        userStore.userInfo.account,
        form.value.bankCardId,
        month,
        `20${year}`,
        form.value.cvv,
      )
    }

    uni.hideLoading()
    emit('success')
    close()
  } catch (error) {
    uni.showToast({
      title: 'Payment failed',
      icon: 'none',
    })
  }
}

const show = async () => {
  popup.value.open()
  initSavedCard()

  // 检查是否可以享受折扣
  try {
    const data = await canOfferDiscount()
    isDiscounted.value = data
  } catch (error) {
    console.error('Failed to check discount:', error)
  }
}

const close = () => {
  popup.value.close()
}

defineExpose({ show })
</script>

<style lang="scss" scoped>
.payment-popup {
  background: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-size: 18px;
      font-weight: bold;
    }

    .close {
      font-size: 24px;
      color: #666;
    }
  }

  .form-item {
    margin-bottom: 15px;

    .label {
      display: block;
      margin-bottom: 5px;
      color: #666;
    }

    input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;

      &:disabled {
        background: #f5f5f5;
      }
    }
  }

  .form-row {
    display: flex;
    gap: 15px;

    .form-item {
      flex: 1;
    }
  }

  .amount {
    margin: 20px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .price {
      font-size: 20px;
      font-weight: bold;
      color: #f60;
    }

    .discount-label {
      font-size: 14px;
      color: #52c41a;
      margin-left: 8px;
    }
  }

  .pay-btn {
    width: 100%;
    padding: 12px;
    background: #007aff;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-size: 16px;
  }
}
</style>
